package com.xlongwei.config;

import java.util.concurrent.TimeUnit;

import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class LogFilter implements Filter {
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        if (log.isDebugEnabled()) {
            log.debug("{} {}", ctx.method(), ctx.path());
            if (!ctx.paramMap().isEmpty()) {
                log.debug("params {}", ctx.paramMap());
            }
            if (StrUtil.isNotBlank(ctx.bodyNew())) {
                log.debug("body {}", ctx.bodyNew());
            }
            StopWatch stopWatch = new StopWatch(StrUtil.EMPTY, false);
            stopWatch.start();
            chain.doFilter(ctx);
            stopWatch.stop();
            log.debug("res({}) {}", stopWatch.getTotal(TimeUnit.MICROSECONDS), ctx.result);
        } else {
            chain.doFilter(ctx);
        }
    }
}
